package com.wangzemin.leetcode.num25;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || k == 1) {
            return head;
        }
        ListNode virNode = new ListNode(-1);
        virNode.next = head;

        ListNode revertPre = virNode;
        ListNode revertHead = virNode.next;
        ListNode revertTail = revertHead;

        int count = k;
        while (revertTail != null) {

            if (count <= 1) {
                count = k;
                ListNode revertSuf = revertTail.next;
                revertTail.next = null;
                revertPre.next = null;

                revertList(revertHead);
                revertPre.next = revertTail;
                revertHead.next = revertSuf;

                revertPre = revertHead;
                revertHead = revertPre.next;
                revertTail = revertHead;
                continue;
            }
            count--;
            revertTail = revertTail.next;
        }
        return virNode.next;
    }

    private void revertList(ListNode revertHead) {
        ListNode pre = null;
        ListNode cur = revertHead;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
    }
}